package com.ayf.payment.game.api.channel.qcjh;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.bean.BaseResData;
import com.ayf.payment.game.api.channel.BaseHandler;
import com.ayf.payment.game.api.dto.platform.SubstitutePayConfigDTO;
import com.ayf.payment.game.api.dto.platform.pay.WanXiangPayConfigParamVO;
import com.ayf.payment.game.api.exception.NullSetException;
import com.ayf.payment.game.api.httpclient.HttpUtils;
import com.ayf.payment.game.api.service.payment.qcjh.util.QCJHSignUtil;
import com.ayf.payment.game.api.service.platform.SubstitutePayConfigService;
import com.ayf.payment.game.api.type.MerchantPayOrderStatusEnum;
import com.ayf.payment.game.api.utils.BigDecimalUtil;
import com.ayf.payment.game.api.utils.RandomStrUtils;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;
import java.util.TreeMap;

@Component
public class QCJHPayHander implements BaseHandler {

    @Autowired
    private SubstitutePayConfigService substitutePayConfigService;

    @Override
    public JSONObject orderCreate(JSONObject inputParam) {
        JSONObject resJson = new JSONObject();
        String merchantOrderNo = inputParam.getString("merchant_order_no");
        resJson.put("merchantOrderNo", merchantOrderNo);
        resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());

        String methodDesc = "七彩聚合代付下单";
        String traceId = inputParam.getString("traceId");
        Integer substitutePayConfigId = inputParam.getInteger("substitutePayConfigId");
        SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(substitutePayConfigId);
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = substitutePayConfigDTO.getWanXiangPayConfigParamVO();

        BaseResData baseResData = orderCreate(traceId,methodDesc,wanXiangPayConfigParamVO,inputParam);
        if (baseResData.isProcessing()){
            resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());
        } else {
            if (baseResData.isSuccess()){
                JSONObject jsonResult = JSONObject.parseObject(baseResData.getData());
                String ret_code = jsonResult.getString("ret_code");
                String message = jsonResult.getString("ret_msg");
                if ("0".equals(ret_code)){
                    String status = jsonResult.getString("status");
                    if ("1".equals(status)){
                        resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());
                    } else {
                        resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                        resJson.put("failReason",message);
                        LogPortal.error("{} {}失败，请求接口成功，接口返回错误码:{} 错误描述:{}",traceId,methodDesc,ret_code,message);
                    }
                } else {
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                    resJson.put("failReason",message);
                    LogPortal.error("{} {}失败，请求接口成功，接口返回错误码:{} 错误描述:{}",traceId,methodDesc,ret_code,message);
                }
            } else {
                resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                resJson.put("failReason",baseResData.getRespMsg());
                LogPortal.error("{} {}失败，请求接口失败，返回错误码:{} 错误描述:{}",traceId,methodDesc,baseResData.getRespCode(),baseResData.getRespMsg());
            }
        }
        LogPortal.info("{} {} 响应报文[{}]", traceId,methodDesc,resJson.toJSONString());
        return resJson;
    }

    @Override
    public JSONObject orderQuery(JSONObject inputParam) {
        JSONObject resJson = new JSONObject();
        String merchantOrderNo = inputParam.getString("merchant_order_no");
        resJson.put("merchantOrderNo", merchantOrderNo);
        resJson.put("status", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());

        String traceId = inputParam.getString("traceId");
        String methodDesc = "七彩聚合代付订单查询";

        Integer substitutePayConfigId = inputParam.getInteger("substitutePayConfigId");
        SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(substitutePayConfigId);
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = substitutePayConfigDTO.getWanXiangPayConfigParamVO();
        BaseResData baseResData = orderQuery(traceId,methodDesc,wanXiangPayConfigParamVO,merchantOrderNo);
        if (baseResData.isProcessing()){
            LogPortal.error("{} 订单号[{}] {}失败 请求接口成功，接口响应超时",traceId,methodDesc,merchantOrderNo);
            return resJson;
        }
        if (baseResData.isSuccess()){
            JSONObject jsonResult = JSONObject.parseObject(baseResData.getData());
            String ret_code = jsonResult.getString("ret_code");
            String message = jsonResult.getString("ret_msg");
            if ("0".equals(ret_code)){
                // 订单状态，0处理中1成功 2失败
                String order_status = jsonResult.getString("status");
                if (StringUtils.isEmpty(order_status) || "0".equals(order_status)){
                    return resJson;
                }
                if ("1".equals(order_status)){
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
                } else if ("2".equals(order_status)){
                    resJson.put("status", MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
                    resJson.put("failReason","接口返回失败");
                }
            } else {
                LogPortal.error("{} {}失败，请求接口成功，渠道返回错误码:{} 错误描述:{}",traceId,methodDesc,ret_code,message);
            }
        } else {
            LogPortal.error("{} {}失败 请求接口失败，错误码:{} 错误描述:{}",traceId,methodDesc,baseResData.getRespCode(),baseResData.getRespMsg());
        }
        LogPortal.info("{} {} 订单号:{} 响应报文[{}]", traceId,methodDesc,merchantOrderNo,resJson.toJSONString());
        return resJson;
    }

    @Override
    public JSONObject balanceQuery(JSONObject inputParam) {
        JSONObject resJson = new JSONObject();
        String traceId = inputParam.getString("traceId");
        String bankName = inputParam.getString("bankName");
        String bankType = getBankType(traceId, bankName);
        if (StringUtils.isEmpty(bankType)) {
            resJson.put("status", "2");
            return resJson;
        }
        resJson.put("status", "1");
        resJson.put("balance", "10000000.00");
        return resJson;
    }

    private BaseResData orderCreate(String traceId, String methodName,WanXiangPayConfigParamVO wanXiangPayConfigParamVO,JSONObject inputParam){
        String merchantOrderNo = inputParam.getString("merchant_order_no");
        String AuthorizationURL = wanXiangPayConfigParamVO.getWebsite();
        String notifyUrl = wanXiangPayConfigParamVO.getNotifyurl();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} {} 失败，通道代付地址不能为空，订单号:{}",traceId,methodName,merchantOrderNo);
            throw new NullSetException(traceId + "代付订单下单失败，请稍后重试！");
        }
        if (StringUtils.isEmpty(notifyUrl)){
            LogPortal.error("{} {} 失败，代付异步通知地址不能为空，订单号:{}",traceId,methodName,merchantOrderNo);
            throw new NullSetException(traceId + "代付异步通知地址不能为空，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        if (!notifyUrl.endsWith("/")){
            notifyUrl=notifyUrl.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("payinterface/df/json");

        BigDecimal amount = inputParam.getBigDecimal("amount");
        String username = inputParam.getString("account_name");
        String bankName = inputParam.getString("bank_name");
        String bankCode = getBankType(traceId, bankName);
        String bankno = inputParam.getString("account_no");

        Map<String,String> reqParam = new TreeMap<>();
        reqParam.put("custid",wanXiangPayConfigParamVO.getParter());
        reqParam.put("out_trade_no",merchantOrderNo);
        String sign = QCJHSignUtil.getSign(traceId,methodName,reqParam,wanXiangPayConfigParamVO.getKey());
        reqParam.put("sign",sign);
        reqParam.put("total_fee",String.valueOf(BigDecimalUtil.yuanToFen(amount)));// 代付金额,单位分
        reqParam.put("name",username);
        reqParam.put("cardNo",bankno);
        reqParam.put("openBank",bankCode);// 银行id，见附录
        reqParam.put("notify_url",notifyUrl.concat("gameapip/v/qcjh/pay/paynotify"));
        reqParam.put("service","pay.df.native");
        reqParam.put("attach","");// 说明： 银行代码，开户行，支行，卡号，电话，身份证，省，市
        BaseResData result = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return result;
    }


    private BaseResData orderQuery(String traceId, String methodName,WanXiangPayConfigParamVO wanXiangPayConfigParamVO,String merchantOrderNo){
        String AuthorizationURL = wanXiangPayConfigParamVO.getWebsite();
        if (StringUtils.isEmpty(AuthorizationURL)){
            LogPortal.error("{} 失败，通道代付订单查询地址不能为空，订单号:{}",traceId,merchantOrderNo);
            throw new NullSetException(traceId + "代付订单查询失败，请稍后重试！");
        }
        if (!AuthorizationURL.endsWith("/")){
            AuthorizationURL=AuthorizationURL.concat("/");
        }
        AuthorizationURL=AuthorizationURL.concat("payinterface/df/query");

        Map<String,String> reqParam = new TreeMap<>();
        reqParam.put("userId",wanXiangPayConfigParamVO.getParter());
        reqParam.put("custSn",merchantOrderNo);
        BaseResData result = HttpUtils.sendPostForm(traceId,methodName,AuthorizationURL,reqParam);
        return result;
    }


    private String getBankType(String traceId, String bankName) {
        if (bankName.contains("农业银行")) {
            return "abc";
        } else if (bankName.contains("中国银行")) {
            return "boc";
        } else if (bankName.contains("建设银行")) {
            return "ccb";
        } else if (bankName.contains("交通银行")) {
            return "comm";
        } else if (bankName.contains("招商银行")) {
            return "cmb";
        } else if (bankName.contains("广东发展银行")||bankName.contains("广发银行")) {
            return "cgb";
        } else if (bankName.contains("中信银行")) {
            return "cncb";
        } else if (bankName.contains("民生银行")) {
            return "cmsb";
        } else if (bankName.contains("光大银行")) {
            return "ceb";
        } else if (bankName.contains("平安银行")) {
            return "pab";
        } else if (bankName.contains("浦发银行")||bankName.contains("浦东发展")) {
            return "spdb";
        } else if (bankName.contains("邮政储蓄")) {
            return "psbc";
        } else if (bankName.contains("华夏银行")) {
            return "hxb";
        } else if (bankName.contains("兴业银行")) {
            return "cib";
        }else if (bankName.contains("工商银行")) {
            return "icbc";
        }else if (bankName.contains("深圳发展银行")) {
            return "sdb";
        }else if (bankName.contains("上海银行")) {
            return "shb";
        }else if (bankName.contains("北京银行")) {
            return "bjb";
        }else if (bankName.contains("浙商银行")||bankName.contains("浙江网商银行")) {
            return "zsb";
        }else if (bankName.contains("渤海银行")) {
            return "cbhb";
        }else if (bankName.contains("恒丰银行")) {
            return "eqb";
        } else {
            LogPortal.error("[{}]七彩聚合代付银行类别错误[{}]", traceId, bankName);
            return null;
        }
    }

    private static void testOrderCreate(){
        String traceId =  SnowFlakeUtils.getTraceId();
        JSONObject inputParam = new JSONObject();
        inputParam.put("merchant_order_no","Y".concat(RandomStrUtils.createRandom(true,8)));
        inputParam.put("amount","1");
        inputParam.put("account_name","张三");
        inputParam.put("bank_name","招商银行");
        inputParam.put("account_no","6225880132496432");
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = getTestWanXiangPayConfigParamVO();
        QCJHPayHander zhuoFuTongPayHandler = new QCJHPayHander();
        zhuoFuTongPayHandler.orderCreate(traceId,"七彩聚合代付下单",wanXiangPayConfigParamVO,inputParam);
    }


    private static void testOrderQuery(){
        String traceId =  SnowFlakeUtils.getTraceId();
        String merchantOrderNO = "Y2021030194487019";
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = getTestWanXiangPayConfigParamVO();
        QCJHPayHander zhuoFuTongPayHandler = new QCJHPayHander();
        zhuoFuTongPayHandler.orderQuery(traceId,"七彩聚合代付订单查询",wanXiangPayConfigParamVO,merchantOrderNO);
    }



    /**
     * 构造测试请求通道商户参数
     * @return
     */
    private static WanXiangPayConfigParamVO getTestWanXiangPayConfigParamVO(){
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = new WanXiangPayConfigParamVO();
        wanXiangPayConfigParamVO.setWebsite("https://www.52gmpay.com");
        wanXiangPayConfigParamVO.setParter("10246");
        wanXiangPayConfigParamVO.setKey("5153238115d2489d8ebea06c69dad1dd");
        wanXiangPayConfigParamVO.setNotifyurl("http://uatxy.xyouplay.com");
        return wanXiangPayConfigParamVO;
    }

    public static void main(String[] args) {
        testOrderCreate();
//        testOrderQuery();
    }
}
